package cn.e3mall.search.utils;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendMail {
    public static void sendEmail(String subject,String text) throws MessagingException {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth","true");//设置访问smtp服务器需要认证
        properties.setProperty("mail.transport.protocol","smtp");//设置访问服务器的协议

        Session session = Session.getDefaultInstance(properties);
        session.setDebug(true);//打开debug功能

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("jiangbinint@163.com"));//设置发件人
        message.setSubject(subject);//设置主体
        message.setText(text);//设置邮件内容

        Transport transport = session.getTransport();
        //连接邮箱smtp服务器，25为默认端口
        transport.connect("smtp.163.com",25,"jiangbinint@163.com","qq1234567891603");
        //要发送到哪个邮箱
        transport.sendMessage(message,new Address[]{new InternetAddress("jiangbinlan@foxmail.com")});
        transport.close();//关闭连接
    }

    public static void groupSendMail(String subject,String content) throws MessagingException {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth","true");//设置访问smtp服务器需要认证
        properties.setProperty("mail.transport.protocol","smtp");//设置访问服务器的协议
        properties.setProperty("mail.host","smtp.163.com");

        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //授权的邮箱
                return new PasswordAuthentication("jiangbinint@163.com", "qq1234567891603");
            }
        });

        session.setDebug(true);//打开debug功能

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("jiangbinint@163.com"));//邮件发送者
        message.setSubject(subject);//设置发送主体
        message.setContent(content,"text/html;charset=utf-8");//设置发送内容，"text/html;charset=utf-8"，表明这是一封html邮件
        //群发的邮箱
        message.setRecipients(MimeMessage.RecipientType.TO,InternetAddress.parse("jiangbinlan@foxmail.com,jiangbinint@163.com"));
        Transport.send(message);
    }

    public static void main(String[] args) {
        try {
            groupSendMail("测试","内容管理系统出现重大错误，请即使处理");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
